<template>
  <!-- 模态层 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <div class="close" @click="changeIsShowModal(false)"></div>
      <nav class="navs">
        <a
          href="javascript:;"
          :class="{ active: isShowPhoneLogin }"
          @click="isShowPhoneLogin = true"
          >手机号登录</a
        >
        |
        <a
          href="javascript:;"
          :class="{ active: !isShowPhoneLogin }"
          @click="showQrCode"
          >微信扫码登录</a
        >
      </nav>
      <div class="content">
        <!-- 手机 -->
        <div class="phone_login" v-show="isShowPhoneLogin">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :msg="msg"
              :imgs="imgs"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model="yzmCode"
            />
            <button class="btn btnCode" @click="getCode" v-show="!showCount">
              获取验证码
            </button>
            <button class="btn btnCode" v-show="showCount">{{ count }}S</button>
          </div>
          <div class="row">
            <button class="btn btnLogin" @click="LoginFn">登录</button>
          </div>
        </div>
        <!-- 微信 -->
        <div id="weixin" class="qrlogin" v-show="!isShowPhoneLogin">
          微信扫码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 辅助函数
import { mapMutations, mapActions } from "vuex";
import { toVerifyPhone } from "@/utils";
// 接口
import { sendSmsAPI, phoneReginAPI, BangDingAPI } from "@/request/api.js";
export default {
  data() {
    return {
      // 控制手机和微信 的切换
      isShowPhoneLogin: true,
      //滑块提示信息
      msg: "向右滑动",
      //滑块背景图
      imgs: [
        require("@/assets/img/integral-01.9386d4bf.png"),
        require("@/assets/img/integral-02.150d92a1.png"),
        require("@/assets/img/integral-03.9870f3f1.png"),
        require("@/assets/img/integral-04.afadcbdf.png"),
      ],
      // 手机号码
      phoneNumber: "",
      // 验证码
      yzmCode: "",
      // 倒计时
      count: 5,
      // 显示倒计时
      showCount: false,
    };
  },
  methods: {
    ...mapMutations({
      // 登录框
      changeIsShowModal: "ShowModal/changeIsShowModal",
      // 登录状态
      changeIsShowLogin: "LoginState/changeIsShowLogin",
      // 提示组件
      changeIsShowToast: "ShowToast/changeIsShowToast",
      // 用户信息
      changeUserInfo: "userInfo/changeUserInfo",
    }),
    ...mapActions({
      asyncToast: "ShowToast/asyncToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 封装函数 验证手机和滑块
    toVerify() {
      // 1.判断手机
      if (!toVerifyPhone(this.phoneNumber)) {
        this.asyncToast({
          showToast: true,
          text: "请输入正确的手机号码！谢谢！",
          type: "danger",
        });
        return;
      }
      // 2.判断滑动
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncToast({
          showToast: true,
          text: "知道会很烦，但麻烦请正确滑动拼图！",
          type: "danger",
        });
        return;
      }
      return true;
    },

    // 获取验证码
    async getCode() {
      // 1.判断手机 和 滑块
      let res = this.toVerify();
      if (!res) return;
      // 2.发送请求
      let req = await sendSmsAPI({
        phone: this.phoneNumber.trim(),
      });
      // console.log("短信", req);
      // 3.请求成功，倒计时
      if (!req) return;
      if (req.code == 0) {
        // 显示倒计时
        this.showCount = true;
        // 定时器
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            clearInterval(timer);
            this.count = 5;
            this.showCount = false;
          }
        }, 1000);
      }
    },

    // 登录按钮
    async LoginFn() {
      // 1.手机号 滑动判断
      let res = this.toVerify();
      if (!res) return;
      // 2.验证码非空校验
      if (!this.yzmCode) {
        this.asyncToast({
          showToast: true,
          text: "亲，验证码不能为空哦！！！！",
          type: "danger",
        });
        return;
      }
      // 判断是否有uuid ，有就是微信绑定手机号,没有就正常登录
      let uuid = localStorage.getItem("uuid");
      let req = null;
      if (uuid) {
        req = await BangDingAPI({
          phone: this.phoneNumber,
          verifyCode: this.yzmCode,
          uuid,
        });
      } else {
        // 3.发送正常登录请求
        req = await phoneReginAPI({
          verifyCode: this.yzmCode,
          phone: this.phoneNumber,
        });
      }
      if (!req) return;
      // 4.请求成功，提示登录成功，关闭登录框，存储 token值
      if (req.code == 0) {
        this.asyncToast({
          showToast: true,
          text: "历经九九八十一难，登录成功！！！！",
          type: "success",
        });
        localStorage.setItem("x-auth-token", req["x-auth-token"]);
        this.changeIsShowModal(false);
        // 5. 改变登录状态 显示购物车
        this.changeIsShowLogin(true);

        // 6.清除 uuid
        localStorage.removeItem("uuid");

        // 显示用户信息
        this.asyncChangeUserInfo();
      }
    },

    // 微信扫码登录
    showQrCode() {
      this.isShowPhoneLogin = false;
      // 微信登录第一步：申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0KLmltcG93ZXJ",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    width: 555px;
    height: 423px;
    background: url("@/assets/img/login-box-bg.png");
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    .close {
      background: url("@/assets/img/close.png");
      width: 22px;
      height: 22px;
      position: absolute;
      right: 66px;
      top: 12px;
      cursor: pointer;
    }
    .navs {
      text-align: center;
      margin-top: 50px;
      a {
        text-decoration: none;
        color: black;
        &.active {
          color: blue;
        }
      }
    }
    .content {
      width: 355px;
      margin: 35px auto 0;
      // 手机
      .phone_login {
        .row {
          display: flex;
          margin-bottom: 20px;
          input {
            flex: 1;
            outline: none;
            height: 40px;
            text-indent: 1em;
          }
          .btn {
            background-color: #12358d;
            color: #fff;
            cursor: pointer;
          }
          .btnCode {
            margin-left: 10px;

            width: 83px;
          }
          .btnLogin {
            flex: 1;
            height: 40px;
          }
        }
      }
      // 微信
      .qrlogin {
        text-align: center;
      }
    }
  }
}
// 滑块插件样式
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>